// global

import path from "path";
import { pathToFileURL } from 'url';
import fg from "fast-glob";

// global ENV
global.AUTO_REST_API = true;

global.sleep = ms => new Promise(r => setTimeout(r, ms));

global.metaGlob = async (rules, dir = process.cwd()) => {
  let read_js_files = fg.globSync(rules, {
    cwd: fg.convertPathToPattern(dir), // trans
    onlyFiles: true,
    ignore: ['**/node_modules/**']
  });

  let _code_res = {};
  for (let tmp of read_js_files) {
    let code_file_path = path.join(dir, tmp);
    _code_res[tmp] = await import(pathToFileURL(code_file_path));
  }
  return _code_res;
};

// 日期格式化
Date.prototype.format = function(format) {
  let date = this;

  // 定义格式化函数
  let formatComponent = function (component) {
    return (date['get' + component]() < 10 ? '0' : '') + date['get' + component]();
  };

  // 替换格式字符串中的各个组件
  return format
    .replace(/yyyy/g, formatComponent('FullYear'))
    .replace(/yy/g, formatComponent('Year').slice(-2))
    .replace(/MM/g, formatComponent('Month') + 1)
    .replace(/dd/g, formatComponent('Date'))
    .replace(/HH/g, formatComponent('Hours'))
    .replace(/mm/g, formatComponent('Minutes'))
    .replace(/ss/g, formatComponent('Seconds'));
}

// 获取当前时间
Date.nowStr = function() {
  return new Date().format("yyyy-MM-dd HH:mm:ss");
}

